package com.cmd;


import com.alibaba.fastjson.JSONObject;
import com.mgr.DriverOrderMgr;
import com.mgr.UserOrderMgr;
import com.player.User;
import com.qy.bean.OrderDriver;
import com.qy.bean.OrderInfo;
import com.qy.util.RedisPoolMgr;
import com.qy.util.StaticData;
import com.util.AbstractCommand;
import com.util.BaoShangCarUtil;
import com.util.PBMessage;

public class GetQRCodeCMD extends AbstractCommand{

	@Override
	public void execute(User user, PBMessage packet) throws Exception {
	    JSONObject reJs = new JSONObject();
		JSONObject param = packet.getMessage();
		if (!param.containsKey("orderId")) {
		    reJs.put(StaticData.reKey.code.getKey(),StaticData.codeType.param_error.getType());
		    user.sendPacket(reJs);
		    return;
		}
		// 订单号
		int orderId = param.getInteger("orderId");
		OrderInfo info = UserOrderMgr.getOrderInfo(orderId);
		if (info == null
			|| info.getOrderStatus() != StaticData.OrderStatus.ARRIVE_NOT_CHECK.getType()
			|| info.getOrderStatus() != StaticData.OrderStatus.START_NOT_ARRIVE_STATION.getType()
			|| info.getOrderStatus() != StaticData.OrderStatus.ACCEPT_NOT_CHECK.getType()
			|| info.getOrderStatus() != StaticData.OrderStatus.ARRIVE_COUNT_DOWN.getType()) {
		    reJs.put(StaticData.reKey.code.getKey(),StaticData.codeType.QR_STATUS_ERROR.getType());
		    user.sendPacket(reJs);
		    return;
		}
		/*
		 * 1.如果是取车，是车主获取二维码
		 * 2.如果是送车去检车站，是送车司机获取二维码
		 * 3.如果是检车完毕，是检车员获取二维码
		 * 4.如果是还车，是车主获取二维码
		 * 验证身份
		 */
		int checkId = StaticData.no_param;
		OrderDriver od = null;
		if(info.getOrderStatus() == StaticData.OrderStatus.START_NOT_ARRIVE_STATION.getType()){
		    od = DriverOrderMgr.getDriverOrder(info.getFDriver());
		    checkId = od.getDriverId();
		}else if(info.getOrderStatus() == StaticData.OrderStatus.ACCEPT_NOT_CHECK.getType()){
		    od = DriverOrderMgr.getDriverOrder(info.getSDriver());
		    checkId = od.getDriverId();
		}else{
		    checkId = info.getUserId();
		}
		if(checkId!=user.getID()){
		    reJs.put(StaticData.reKey.code.getKey(),StaticData.codeType.QR_STATUS_ERROR.getType());
		    user.sendPacket(reJs);
		    return;
		}
		
		/*
		 * 成功则添加到redis中
		 */
		String imagePath = (String) RedisPoolMgr.get(BaoShangCarUtil.getImageKey(info), 
			String.class);
		if(imagePath==null){
			imagePath = BaoShangCarUtil.createOrderQR(BaoShangCarUtil.getImageKey(info));
			if(imagePath!=null){
			    RedisPoolMgr.set(BaoShangCarUtil.getImageKey(info), imagePath,24*60*60);
			}
		}
		
		if (imagePath == null||imagePath.isEmpty()) {
		    reJs.put(StaticData.reKey.code.getKey(),StaticData.codeType.not_exist2.getType());
		    user.sendPacket(reJs);
		    return;
		}
		
		reJs.put("imagePath", imagePath);
		reJs.put(StaticData.reKey.code.getKey(), StaticData.codeType.ok.getType());
		reJs.put(StaticData.reKey.cmd.getKey(),packet.getCode());
		user.sendPacket(reJs);
	}

}
